package leetcode.od;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;

/**
 * @author pppppp
 * @date 2022/4/11 17:07
 *   乱序数组，删除所有重复元素 使得每个元素只出现一次，
 *     并且按照出现的次数的由高到低进行排序
 *     相同出现次数，按照第一次出现的顺序进行先后排序（要求稳定）
 */
public class 乱序数组 {
    @Test
    public void T_0() {
        int[][] nums = {{3,3,2,1,1},{1,2,3},{1,1,1,2,3,3,3,3}};
        int[][] ans = {{3,1,2},{1,2,3},{3,1,2}};
        for (int i = 0; i < nums.length; i++) {
            System.out.println(Arrays.equals(solution(nums[i]),ans[i]));
        }
    }

    private int[] solution(int[] num) {
        HashMap<Integer, int[]> map = new HashMap<>();
        int[] numcopy = Arrays.copyOfRange(num, 0, num.length);
        for (int i = 0; i < num.length; i++) {
            if(map.containsKey(num[i])){
                int[] n = map.get(num[i]);
                n[1] += 1;
            }else {
                int[] n = new int[]{i,1};
                map.put(num[i],n);
            }
        }
        int[][] res = new int[map.size()][2];
        int index = 0;
        for (Integer key : map.keySet()) {
            int[] value = map.get(key);
            res[index++] = value;
        }
        Arrays.sort(res, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[1] == o2[1]){
                    return o1[0]-o2[0];
                }
                return o2[1] - o1[1];
            }
        });
        int[] ans = new int[res.length];
        for (int i = 0; i < ans.length; i++) {
            ans[i] = numcopy[res[i][0]];
        }
        return ans;
    }
}
